with Ada.Text_Io; use Ada.Text_Io;
with Chaines.Partagees; use Chaines.Partagees;
with Ada.Unchecked_Deallocation;

package body Chaines.Partagees is

   procedure Free is new Ada.Unchecked_Deallocation(String,Ptr_String);

   procedure Initialize (C: in out Chaine_Partagee) is

   begin
      if Trace then
         Put_Line("Initialize");
      end if;
      C.Value := new Partage;
      C.Value.all.Cpt := new Integer(1);
      C.Value.all.Ptr_Chaine :=  new String(1..1);
      C.Value.all.Ptr_Chaine.all := "";
   end Initialize;

   procedure Adjust     ( C : in out Chaine_Partagee ) is
   begin
      if C.Value /= null then
         if C.Value.all.Cpt /= null then
            C.Value.all.Cpt.all := C.Value.all.Cpt.all + 1 ;
         end if;
      end if;
   end Adjust;

   procedure Finalize   ( C : in out Chaine_Partagee )is
   begin
      if C.Value /= null then
         if C.Value.all.Cpt /= null then
            C.Value.all.Cpt.all := C.Value.Cpt.all -1 ;
         end if;
         if C.Value.all.Cpt.all = 0 then
            if C.Value.all.Ptr_Chaine /= null;
              Free(C.Value.all.Ptr_Chaine);
            end if;
         end if;
      end if;
   end Finalize;

   function Partager ( S: String) return Chaine_Partagee is
      C: Chaine_Partagee;
   begin
      C.Value := new Partage;
      C.Value.all.Cpt := new Integer(1);
      C.Value.all.Ptr_Chaine := new String(1..S'Length);
      C.Value.all.Ptr_Chiane.all := S;
   end Partager;

   function Dechainer(C : Chaine_Partagee) return String is
   begin
      if C.Value = null then
         return "";
      else
         if C.Value.all.Ptr_Chaine = null then
            return "";
         else
            return C.Value.all.Ptr_Chaine.all;
         end if;
      end if;
   end Dechainer;

end Chaines.Partagees ;
